﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace Print_UI
{
    public partial class FrmCreateTeacher : CommonForm
    {
        public FrmCreateTeacher()
        {
            InitializeComponent();
        }

        private int _id = -1;
        public bool IsChanged { get; set; }
        private CommandParams _cmd = new CommandParams();
        SqlConnection _Cnn;

        public SqlConnection Cnn
        {
            get { return _Cnn; }
            set { _Cnn = value; }
        }


        private void LoadAuth()
        {
            if (Actions != null)
            {
                if (Actions.Contains("Add"))
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                else
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                if (Actions.Contains("Edit"))
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    AcceptButton = btnSave;
                }
                else
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

            }
        }

        private void CheckAuth(string key)
        {
            if (Actions != null && Actions.Contains(key))
            {
                if (key == "Add")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                if (key == "Edit")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }
            }
        }

        private bool CheckInput()
        {
            bool result = true;
            dxErrorProvider1.ClearErrors();
            if ( txtName.Text == string.Empty)
            {
               
                dxErrorProvider1.SetError(txtName, "Chưa nhập tên giảng viên");
                result = false;
            }
            else
            {
               
                if (txtName.Text == string.Empty)
                {
                    dxErrorProvider1.SetError(txtName, "Chưa nhập tên giảng viên");
                    result = false;
                }

            }
            return result;
        }

       
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                
                Cnn.Open();
                if (CheckInput())
                {
                    var Signature = Model.PRI_Teacher.FirstOrDefault(c => c.ID == _id);
                    object obj = gridView1.GetFocusedRowCellValue("ID");
                    if (Signature != null)
                    {
                        int id = Convert.ToInt32(obj);

                        if (obj != null)
                        {
                            Signature.ModifiedDate = DateTime.Now;
                            Signature.ModifiedBy = UserName;
                            Signature.Code = "";
                            if (txtImage.Text != string.Empty)
                            {
                                Signature.Name = txtName.EditValue.ToString();
                                Signature.Signature = convertImageToBytes();
                            }
                            else
                            {
                                Signature.Name = txtName.EditValue.ToString();
                            }
                            
                            
                        }
                        MessageBox.Show("Cập nhật giảng viên thành công!");
                        Model.SaveChanges();
                        LoadData();
                    }
                    else
                    {
                        if (txtImage.Text !=string.Empty)
                        {
                            string strCom = "insert into PRI_Teacher (Code,Name,DepartmentID,Signature,CreatedDate,CreatedBy) values (@Code,@Name,@DepartmentID,@Signature,@CreatedDate,@CreatedBy)";
                            SqlCommand com = new SqlCommand(strCom, Cnn);
                            com.Parameters.Add("@Code", SqlDbType.NVarChar).Value = "";
                            com.Parameters.Add("@Name", SqlDbType.NVarChar).Value = txtName.Text;
                            com.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = DepartmentID;
                            com.Parameters.Add("@Signature", SqlDbType.Image).Value = convertImageToBytes();
                            com.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = DateTime.Now;
                            com.Parameters.Add("@CreatedBy", SqlDbType.NVarChar).Value = UserName;
                            com.ExecuteNonQuery();
                        }
                        else
                        {
                           
                            string strCom = "insert into PRI_Teacher (Code,Name,DepartmentID,CreatedDate,CreatedBy) values (@Code,@Name,@DepartmentID,@CreatedDate,@CreatedBy)";
                            SqlCommand com = new SqlCommand(strCom, Cnn);
                            com.Parameters.Add("@Code", SqlDbType.NVarChar).Value = "";
                            com.Parameters.Add("@Name", SqlDbType.NVarChar).Value = txtName.Text;
                            com.Parameters.Add("@DepartmentID", SqlDbType.Int).Value = DepartmentID;
                          
                            com.Parameters.Add("@CreatedDate", SqlDbType.DateTime).Value = DateTime.Now;
                            com.Parameters.Add("@CreatedBy", SqlDbType.NVarChar).Value = UserName;
                            com.ExecuteNonQuery();
                            
                        }
                        
                       
                        MessageBox.Show("Thêm mới giảng viên thành công!");
                        Model.SaveChanges();
                        LoadData();
                    }
                    txtImage.Text=txtName.Text = "";
                    pictureBox1.Image = null;
                  
                    
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally 
            { 
                Cnn.Close(); 
            }
        }
                  
        
        private void LoadData()
        {
            try
            {
                var query = from c in Model.PRI_Teacher
                            
                            select new
                            {
                                c.ID,
                                c.Code,
                                c.Name,
                                c.Signature
                            };
                gvData.DataSource = query;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private byte[] convertImageToBytes()
        {
            
                FileStream fs = new FileStream(txtImage.Text, FileMode.Open, FileAccess.Read);
                byte[] picbyte = new byte[fs.Length];
                fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
                fs.Close();
                return picbyte;
            
        }

        private void FrmCreateTeacher_Load(object sender, EventArgs e)
        {
            Cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
            stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
            LoadData();
        }

        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
               

                object cellValue = gridView1.GetFocusedRowCellValue("ID");
                if (cellValue != null)
                {
                    int id = Convert.ToInt32(cellValue);

                    bool check2 = Model.PRI_SubjectSetting.Where(c => c.TeacherID==id).Count() > 0;
                    if (check2)
                    {
                        CommonMessage("Giảng viên đã được thiết lập cho môn học không được xóa");
                    }
                    else
                    {
                        if (CommonConfirm("Bạn muốn xóa giảng viên này?", "XOA"))
                        {
                            stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                            _id = -1;
                            var obj = Model.PRI_Teacher.FirstOrDefault(c => c.ID == id);
                            if (obj != null)
                            {
                                Model.DeleteObject(obj);
                                Model.SaveChanges();
                                CommonMessage("Xóa thành công");
                                LoadData();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Edit();
               
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void Edit()
        {
            object cellValue = gridView1.GetFocusedRowCellValue("ID");
            if (cellValue != null)
            {
                CheckAuth("Edit");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = Convert.ToInt32(cellValue);
                var obj = Model.PRI_Teacher.FirstOrDefault(c => c.ID == _id);
                if (obj != null)
                {
                    
                    txtName.EditValue = obj.Name;
                    if (obj.Signature != null)
                    {
                        MemoryStream ms = new MemoryStream(obj.Signature);
                        pictureBox1.Image = Image.FromStream(ms);
                    }
                    else
                    {
                        
                        pictureBox1.Image = null;
                    }
                                        
                }

            }
            LoadData();

            
        }

        private void gvData_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                
                DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
                Point pt = view.GridControl.PointToClient(Control.MousePosition);
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = view.CalcHitInfo(pt);
                if (info.InRow || info.InRowCell)
                {
                    Edit();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Dữ liệu chưa được cập nhật. Bạn có muốn thoát không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                btnSave.Enabled = false;
               
                txtName.Text = string.Empty;
                txtImage.Text = string.Empty;
                pictureBox1.Image = null;
            }
        }

        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
               
                txtName.Text = string.Empty;
                txtImage.Text = string.Empty;
                pictureBox1.Image = null;
                CheckAuth("Add");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = -1;
                LoadData();
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = openFileDialog.Filter = "Image|*.jpg;*jpeg;*.gif;*.png;*.bmp";
            openFileDialog.FilterIndex = 1;
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.ImageLocation = openFileDialog.FileName;
                txtImage.Text = openFileDialog.FileName;
            }
            
        }

        

       
    }
}